package com.dnjn.happiness.survey.controller.admin;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dnjn.happiness.common.cloud.controller.BaseController;
import com.dnjn.happiness.common.core.constant.SecurityConstants;
import com.dnjn.happiness.common.core.domain.R;
import com.dnjn.happiness.common.core.exception.job.TaskException;
import com.dnjn.happiness.common.core.model.PositionLadderVO;
import com.dnjn.happiness.common.core.model.SysPostVO;
import com.dnjn.happiness.common.core.utils.StringUtils;
import com.dnjn.happiness.common.core.web.domain.AjaxResult;
import com.dnjn.happiness.common.log.annotation.Log;
import com.dnjn.happiness.common.log.enums.BusinessType;
import com.dnjn.happiness.common.security.annotation.InnerAuth;
import com.dnjn.happiness.common.security.annotation.RequiresPermissions;
import com.dnjn.happiness.common.security.utils.SecurityUtils;
import com.dnjn.happiness.survey.api.model.StatisticalAnalysisModel;
import com.dnjn.happiness.survey.domain.Survey;
import com.dnjn.happiness.survey.domain.SurveyIntervalScore;
import com.dnjn.happiness.survey.domain.SurveyRecord;
import com.dnjn.happiness.survey.domain.SurveyTemplate;
import com.dnjn.happiness.survey.domain.TikuTags;
import com.dnjn.happiness.survey.domain.vo.StatisticalAnalysisAppriseVO;
import com.dnjn.happiness.survey.service.ISurveyIntervalScoreService;
import com.dnjn.happiness.survey.service.ISurveyRecordService;
import com.dnjn.happiness.survey.service.ISurveyService;
import com.dnjn.happiness.survey.service.ISurveyTemplateService;
import com.dnjn.happiness.survey.service.ITikuTagsService;
import com.dnjn.happiness.system.api.RemoteDeptService;
import com.dnjn.happiness.system.api.RemotePostService;
import com.dnjn.happiness.system.api.RemoteUserService;
import com.dnjn.happiness.system.api.domain.SysDept;
import com.dnjn.happiness.system.api.domain.SysRole;
import com.dnjn.happiness.system.api.domain.SysUser;
import com.dnjn.happiness.system.api.model.LoginUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 问卷Controller
 *
 * @author happiness
 * @date 2023-10-23
 */
@Tag(name = "admin survey survey 问卷", description = "问卷")
@RestController
@RequestMapping("/admin/survey")
public class AdminSurveyController extends BaseController {
    @Autowired
    private ISurveyService surveyService;

    @Autowired
    private ITikuTagsService tikuTagsService;

    @Autowired
    private ISurveyRecordService recordService;

    @Autowired
    private RemoteUserService userService;

    @Autowired
    private ISurveyTemplateService surveyTemplateService;

    @Autowired
    private ISurveyIntervalScoreService intervalScoreService;

    @Autowired
    private RemotePostService postService;

    @Autowired
    private RemoteDeptService deptService;

    @InnerAuth
    @PostMapping("/admin/survey/selectStatisticalAnalysisSurvryList")
    public R<List<StatisticalAnalysisModel>> selectStatisticalAnalysisSurvryList(@RequestBody StatisticalAnalysisAppriseVO vo){
        return R.ok(surveyService.selectStatisticalAnalysisSurvryList(vo));
    }

    @Operation(summary = "getSurveyList 第一版本-统计-问卷列表")
    @RequiresPermissions("@ss.hasPermi('biz:statistical:list')")
    @GetMapping("/selectSurvey")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getSurveyList() {

        List<Survey> list = surveyService.lambdaQuery().eq(Survey::getDeleted, '0').list();
        return success(list);

    }


    /**
     * 根据问卷id查询问卷
     */
    @Operation(summary = "根据问卷id查询问卷")
    @GetMapping("/get/{surveyId}")
    @RequiresPermissions("@ss.hasPermi('survey:survey:query')")
    @Log(title = "biz", businessType = BusinessType.SELECT)
    public AjaxResult getSurvey(@PathVariable Long surveyId) {
        Survey survey = surveyService.getById(surveyId);

        if (null != survey) {
            List<Long> userids = new ArrayList<>();
            List<SurveyRecord> surveyRecordList = recordService.lambdaQuery().eq(SurveyRecord::getSurveyId, surveyId).list();
            if (!CollectionUtils.isEmpty(surveyRecordList) && surveyRecordList.size() > 0) {
                List<SysUser> userList = new ArrayList<>();
                userids = surveyRecordList.stream().map(item -> {
                    return item.getUserId();
                }).collect(Collectors.toList());
            }
            survey.setUserIds(userids);
            List<SurveyRecord> recordList = new ArrayList<>();
            String checkedUserIds = survey.getCheckedUserIds();
            if (!StringUtils.isEmpty(checkedUserIds)) {
                for (String userIdStr : checkedUserIds.split(",")) {
                    Long userId = Long.parseLong(userIdStr);
                    R<SysUser> userResult = userService.selectUserInfo(userId, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(userResult) && StringUtils.isNotNull(userResult.getData())) {
                        SysUser user = userResult.getData();
                        if (null != user) {
                            SurveyRecord surveyRecord = new SurveyRecord();
                            surveyRecord.setUserId(userId);
                            surveyRecord.setNickName(user.getNickName());
                            recordList.add(surveyRecord);
                        }
                    }
                }
            }
            survey.setRecordList(recordList);

            //回显部门名称,岗位名称,职级名称
            if (!StringUtils.isEmpty(survey.getDeptIds())) {
                List<SysDept> deptList = new ArrayList<>();
                String deptIds = survey.getDeptIds();
                String[] split = deptIds.split(",");
                for (String deptIdStr : split) {
                    SysUser user = new SysUser();
                    long deptId = Long.parseLong(deptIdStr);
                    user.setDeptId(deptId);
                    R<List<SysUser>> result = userService.selectUserList(user, SecurityConstants.INNER);
                    List<SysUser> sysUserList = new ArrayList<>();
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                        sysUserList = result.getData();
                    }

                    SysDept dept = null;
                    R<SysDept> remoteResult = deptService.getInfoById(deptId, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(remoteResult) && StringUtils.isNotNull(remoteResult.getData())) {
                        dept = remoteResult.getData();
                    }
                    if (null != dept) {
                        dept.setCount(sysUserList.size());
                        deptList.add(dept);
                    }
                }
                survey.setSelectDeptList(deptList);
            }
            if (!StringUtils.isEmpty(survey.getPostIds())) {
                List<SysPostVO> postList = new ArrayList<>();
                String[] split = survey.getPostIds().split(",");
                for (String postIdStr : split) {
                    Long postId = Long.parseLong(postIdStr);
                    SysPostVO post = null;
                    R<SysPostVO> postResult = postService.getInfoById(postId, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(postResult) && StringUtils.isNotNull(postResult.getData())) {
                        post = postResult.getData();
                    }
                    if (null != post) {
                        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
                        Map<String, Object> map = new HashMap<>();
                        map.put("postId", postId);
                        map.put("deptId", deptId);
                        R<List<SysUser>> result = userService.getUsersByPostId(map, SecurityConstants.INNER);
                        Integer count = 0;
                        if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                            count = result.getData().size();
                        }
                        post.setCount(count);
                        postList.add(post);
                    }
                }
                survey.setSelectPostList(postList);
            }
            if (!StringUtils.isEmpty(survey.getPositionIds())) {
                List<PositionLadderVO> positionLadderList = new ArrayList<>();
                String[] split = survey.getPositionIds().split(",");
                for (String position : split) {
                    PositionLadderVO positionLadder = new PositionLadderVO();
                    positionLadder.setPositionLadder(position);
                    Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
                    Map<String, Object> map = new HashMap<>();
                    map.put("position", position);
                    map.put("deptId", deptId);
                    R<List<SysUser>> result = userService.getUsersByPosition(map, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                        positionLadder.setCount(result.getData().size());
                    }
                    positionLadderList.add(positionLadder);
                }
                survey.setSelectPosttionList(positionLadderList);
            }
        }
        return success(survey);
    }

    @PostMapping("/querySurveyByUserId")
    @RequiresPermissions("@ss.hasPermi('survey:survey:query')")
    @Operation(summary = "问卷-后台", description = " ② 我的问卷-问卷记录-查看我需要参与的问卷 必传 watchId, 可选:recordStatus(Y|N)")
    public AjaxResult querySurveyByUserId(@RequestBody Survey domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        Page<Survey> list = surveyService.selectPageSurvey(domain, Page.of(current, size).addOrder(OrderItem.desc("survey_id")));

        return success(list);

    }

    @GetMapping("/queryTikutags")
    @RequiresPermissions("@ss.hasPermi('survey:survey:query')")
    public AjaxResult queryTags() {
        List<TikuTags> list = tikuTagsService.lambdaQuery().eq(TikuTags::getDeleted, '0').list();
        return success(list);

    }

    //  我的 -我的问卷
    @PostMapping("/querySurveyByUserId1")
    @RequiresPermissions("@ss.hasPermi('survey:survey:query')")
    public AjaxResult querySurveyByUserId1(@RequestBody Survey domain, @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size) {
        if (whetherAllPermissions()) {
            domain.setWhetherAllPermissions(true);
        } else {
            domain.setWhetherAllPermissions(false);
        }
        if(Objects.isNull(domain.getDeptId())){
            domain.setDeptId(SecurityUtils.getLoginUser().getDeptId());
        }
        Page<Survey> list = surveyService.selectPageSurvey1(domain, Page.of(current, size).addOrder(OrderItem.desc("survey_id")));
        return success(list);

    }

    /**
     * 新增问卷
     */
    @Log(title = "问卷", businessType = BusinessType.INSERT)
    @RequiresPermissions("@ss.hasPermi('survey:survey:add')")
    @PostMapping("/addSurvey")
    @Operation(summary = "添加问卷-后台")
    public AjaxResult add(@RequestBody Survey survey) {
        Long surveyTemplateId = survey.getSurveyTemplateId();
        Assert.notNull(surveyTemplateId, "surveyTemplateId不能为空");
        Assert.notNull(survey.getDateStart(), "开始时间不能为空");
        Assert.notNull(survey.getDateEnd(), "结束时间不能为空");
        Assert.notNull(survey.getSurveyTitle(), "问卷标题不能为空");
        SurveyTemplate surveyTemplate = surveyTemplateService.getById(surveyTemplateId);
        String tikuIds = surveyTemplate.getTikuIds();
        if (StringUtils.isNotEmpty(tikuIds)) {
            survey.setTimuIds(Arrays.asList(tikuIds.split(",")).stream().map(item -> Long.parseLong(item.trim())).collect(Collectors.toList()));
        }
        survey.setQuestionType(surveyTemplate.getQuestionType());
        survey.setSurveyType(surveyTemplate.getSurveyType());
        List<SurveyIntervalScore> intervalScoreList = intervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyTemplateId).list();
        survey.setIntervalScoreList(intervalScoreList);
        survey.setCreateBy(SecurityUtils.getUsername());
        //处理参加人部门列表-》参加人列表
        List<Long> deptIdList = survey.getDeptIdList();
        if (!CollectionUtils.isEmpty(deptIdList) && deptIdList.size() > 0) {
            List<Long> userList = new ArrayList<>();
            //根据部门id查询部门下所有用户id
            for (Long deptId : deptIdList) {
                R<List<Long>> result = userService.selectUserListByDeptIdList(deptId, SecurityConstants.INNER);
                if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                    userList.addAll(result.getData());
                }            }
            if (null != userList && userList.size() > 0) {
                survey.setUserIds(userList);
            }
            String deptIds = deptIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
            survey.setDeptIds(deptIds);
        }
        int i = surveyService.saveSurvey(survey);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("survey", survey);
        return ajax;
    }


    /**
     * 修改问卷
     */
    @Log(title = "问卷", businessType = BusinessType.UPDATE)
    @RequiresPermissions("@ss.hasPermi('survey:survey:edit')")
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody Survey survey) {
        Long surveyTemplateId = survey.getSurveyTemplateId();
        Assert.notNull(surveyTemplateId, "surveyTemplateId不能为空");
        Assert.notNull(survey.getDateStart(), "开始时间不能为空");
        Assert.notNull(survey.getDateEnd(), "结束时间不能为空");
        Assert.notNull(survey.getSurveyTitle(), "问卷标题不能为空");
        SurveyTemplate surveyTemplate = surveyTemplateService.getById(surveyTemplateId);
        String tikuIds = surveyTemplate.getTikuIds();
        if (StringUtils.isNotEmpty(tikuIds)) {
            survey.setTimuIds(Arrays.asList(tikuIds.split(",")).stream().map(item -> Long.parseLong(item.trim())).collect(Collectors.toList()));
        }
        List<SurveyIntervalScore> intervalScoreList = intervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyTemplateId).list();
        survey.setIntervalScoreList(intervalScoreList);
        List<Long> deptIdList = survey.getDeptIdList();
        if (!CollectionUtils.isEmpty(deptIdList) && deptIdList.size() > 0) {
            List<Long> userList = new ArrayList<>();
            //根据部门id查询部门下所有用户id
            for (Long deptId : deptIdList) {
                R<List<Long>> result = userService.selectUserListByDeptIdList(deptId, SecurityConstants.INNER);
                if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                    userList.addAll(result.getData());
                }            }
            if (null != userList && userList.size() > 0) {
                survey.setUserIds(userList);
            }
            String deptIds = deptIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
            survey.setDeptIds(deptIds);
        } else {
            survey.setDeptIds(null);
        }
        int i = surveyService.updateSurvey(survey);
        return toAjax(i);
    }

    /**
     * 删除问卷
     */
    @Log(title = "问卷", businessType = BusinessType.UPDATE)
    @DeleteMapping("/remove/{surveyId}")
    @RequiresPermissions("@ss.hasPermi('survey:survey:remove')")
    public AjaxResult remove(@PathVariable Long surveyId) {
        Assert.notNull(surveyId, "问卷Id不能为空");
        Boolean flag = surveyService.deleteSurvey(surveyId);
        if (flag) {
            return success("删除成功");
        } else {
            return error("删除失败");
        }
    }

    @PostMapping("/endSurveyId")
    @Operation(summary = "我的-我的问卷-结束问卷", description = "surveyId 问卷id")
    @RequiresPermissions("@ss.hasPermi('survey:survey:query')")
    public AjaxResult endSurveyId(@Parameter Long surveyId) {
        surveyService.endSurveyId(surveyId);
        return success();
    }


    @PostMapping("/issuedSurveyId")
    @Operation(summary = "我的-我的问卷-下发问卷", description = "surveyId 问卷id")
    @RequiresPermissions("@ss.hasPermi('survey:survey:query')")
    public AjaxResult issuedSurveyId(@Parameter Long surveyId) throws Exception {

        List<SurveyRecord> list = recordService.lambdaQuery().eq(SurveyRecord::getSurveyId, surveyId).eq(SurveyRecord::getDeleted, "0").list();
        if (list.size() > 0) {
            boolean update = surveyService.lambdaUpdate().eq(Survey::getSurveyId, surveyId).set(Survey::getIssuedStatus, "1").update();


            Survey one = surveyService.lambdaQuery().eq(Survey::getSurveyId, surveyId).one();
            // 结束问卷
            surveyService.endTime(one);
            //标记问卷开始
            surveyService.startTime(one);
        } else {
            return AjaxResult.success("没有答题人");
        }

        return success();

    }


    /**
     * 新增问卷 -架构 岗位 职级
     */
    @Log(title = "问卷", businessType = BusinessType.INSERT)
    @RequiresPermissions("@ss.hasPermi('survey:survey:add')")
    @PostMapping("/insertSurvey")
    @Operation(summary = "添加问卷-后台 架构 岗位 职级")
    public AjaxResult insertSurvey(@RequestBody Survey survey) {
        Long surveyTemplateId = survey.getSurveyTemplateId();
        Assert.notNull(surveyTemplateId, "surveyTemplateId不能为空");
        Assert.notNull(survey.getDateStart(), "开始时间不能为空");
        Assert.notNull(survey.getDateEnd(), "结束时间不能为空");
        Assert.notNull(survey.getSurveyTitle(), "问卷标题不能为空");
        SurveyTemplate surveyTemplate = surveyTemplateService.getById(surveyTemplateId);
        String tikuIds = surveyTemplate.getTikuIds();
        if (StringUtils.isNotEmpty(tikuIds)) {
            survey.setTimuIds(Arrays.asList(tikuIds.split(",")).stream().map(item -> Long.parseLong(item.trim())).collect(Collectors.toList()));
        }
        survey.setQuestionType(surveyTemplate.getQuestionType());
        survey.setSurveyType(surveyTemplate.getSurveyType());
        List<SurveyIntervalScore> intervalScoreList = intervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyTemplateId).list();
        survey.setIntervalScoreList(intervalScoreList);
        survey.setCreateBy(SecurityUtils.getUsername());


        setSurveyUserIds(survey);
        int i = surveyService.saveSurvey(survey);
        //发起钉钉消息工作通知 todo

        AjaxResult ajax = AjaxResult.success();
        ajax.put("survey", survey);
        return ajax;
    }


    /**
     * 修改问卷
     */
    @Log(title = "问卷", businessType = BusinessType.UPDATE)
    @RequiresPermissions("@ss.hasPermi('survey:survey:edit')")
    @PutMapping("/editSurvey")
    public AjaxResult editSurvey(@RequestBody Survey survey) {
        Long surveyTemplateId = survey.getSurveyTemplateId();
        Assert.notNull(surveyTemplateId, "surveyTemplateId不能为空");
        Assert.notNull(survey.getDateStart(), "开始时间不能为空");
        Assert.notNull(survey.getDateEnd(), "结束时间不能为空");
        Assert.notNull(survey.getSurveyTitle(), "问卷标题不能为空");
        SurveyTemplate surveyTemplate = surveyTemplateService.getById(surveyTemplateId);
        String tikuIds = surveyTemplate.getTikuIds();
        if (StringUtils.isNotEmpty(tikuIds)) {
            survey.setTimuIds(Arrays.asList(tikuIds.split(",")).stream().map(item -> Long.parseLong(item.trim())).collect(Collectors.toList()));
        }
        List<SurveyIntervalScore> intervalScoreList = intervalScoreService.lambdaQuery().eq(SurveyIntervalScore::getSurveyId, surveyTemplateId).list();
        survey.setIntervalScoreList(intervalScoreList);

        setSurveyUserIds(survey);
        int i = surveyService.updateSurvey(survey);
        return toAjax(i);
    }


    private void setSurveyUserIds(Survey survey) {
        Set<Long> userIdSet = new HashSet<>();
        if ("dept".equals(survey.getType())) {
            String deptIds = survey.getDeptIds();
            ;
            if (!StringUtils.isEmpty(deptIds)) {
                List<String> list = new ArrayList<>();
                List<Long> deptIdList = new ArrayList<>();
                String[] str = deptIds.split(",");
                list = Arrays.asList(str);
                list.forEach(item -> {
                    deptIdList.add(Long.parseLong(item));
                });
                //根据部门id查询部门下所有用户id
                for (Long deptId : deptIdList) {
                    R<List<Long>> result = userService.selectUserListByDeptIdList(deptId, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())){
                        userIdSet.addAll(result.getData());
                    }
                }
            }
        }
        if ("post".equals(survey.getType())) {
            String postIds = survey.getPostIds();
            if (!StringUtils.isEmpty(postIds)) {
                List<String> list = new ArrayList<>();
                List<Long> postIdList = new ArrayList<>();
                String[] str = postIds.split(",");
                list = Arrays.asList(str);
                list.forEach(item -> {
                    postIdList.add(Long.parseLong(item));
                });
                for (Long postId : postIdList) {
                    Long deptId = SecurityUtils.getLoginUser().getDeptId();
                    Map<String, Object> map = new HashMap<>();
                    map.put("postId", postId);
                    map.put("deptId", deptId);
                    R<List<SysUser>> result = userService.getUsersByPostId(map, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                        userIdSet.addAll(result.getData().stream().map(item -> {
                            return item.getUserId();
                        }).collect(Collectors.toList()));
                    }
                }
            }
        }

        if ("position".equals(survey.getType())) {
            String positionIds = survey.getPositionIds();
            if (!StringUtils.isEmpty(positionIds)) {
                List<String> list = new ArrayList<>();
                String[] str = positionIds.split(",");
                list = Arrays.asList(str);
                for (String position : list) {
                    Long deptId = SecurityUtils.getLoginUser().getDeptId();
                    Map<String, Object> map = new HashMap<>();
                    map.put("position", position);
                    map.put("deptId", deptId);
                    R<List<SysUser>> result = userService.getUsersByPosition(map, SecurityConstants.INNER);
                    if (StringUtils.isNotNull(result) && StringUtils.isNotNull(result.getData())) {
                        userIdSet.addAll(result.getData().stream().map(item -> {
                            return item.getUserId();
                        }).collect(Collectors.toList()));
                    };
                }
            }
        }
        List<Long> userIdList = survey.getUserIds();
        if (!CollectionUtils.isEmpty(userIdList)) {
            survey.setCheckedUserIds(StringUtils.join(userIdList, ","));
            userIdSet.addAll(userIdList);
        } else {
            survey.setCheckedUserIds(null);
        }
        List<Long> userIds = new ArrayList<>(userIdSet);
        survey.setUserIds(userIds);
    }

    @GetMapping("/querySurveyAllByUserId/{userId}")
    @RequiresPermissions("@ss.hasPermi('survey:survey:query')")
    @Operation(summary = "个人画像-问卷记录")
    public AjaxResult querySurveyAllByUserId(@PathVariable Long userId) {
        List<Survey> list = surveyService.querySvrveyAllByUserId(userId);
        return success(list);

    }

    public static Boolean whetherAllPermissions() {
        Boolean flag = false;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (null != loginUser) {
            Set<String> roles = loginUser.getRoles();
            if (!CollectionUtils.isEmpty(roles)) {
                for (String role : roles) {
                    if ("admin".equals(role) || "admin_hq".equals(role)) {
                        flag = true;
                    }
                }
            } else {
                if (1L == loginUser.getUserid()) {
                    flag = true;
                }
            }
        }
        return flag;
    }
}
